package com.itheima.interceptor;


import com.alibaba.fastjson.JSONObject;
import com.css.tliasspringbootstarterautoconfigure.utils.JwtUtils;
import com.itheima.pojo.Result;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class FirstInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtUtils jwtUtils;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //验证JWT
            //获取JWT
        String jwt = request.getHeader("token");
        if(!StringUtils.hasLength(jwt)){//相比token==null多了!str.isEmpty()判断
            Result notLogin = Result.error("NOT_LOGIN");
            String json = JSONObject.toJSONString(notLogin);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(json);
            return false;
        }

            //解析jwt
        try {
            jwtUtils.parseJWT(jwt);
            return true;
        } catch (Exception e) {
            //jwt解析失败，返回登录页面
            Result notLogin = Result.error("NOT_LOGIN");
            String json = JSONObject.toJSONString(notLogin);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(json);
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
